<template>
  <div class="app-container calendar-list-container">
    <div class="apply-query">
      <el-row class="filter-query">
        <el-col><span>{{ $t("bu.queryCriteria") }}</span></el-col>
      </el-row>
      <el-form :inline="true" label-width="100px" style="padding: 0 20px">
        <el-row>
          <el-col :span="4">
            <div class="w20">
              <div class="labelName">{{$t('bu.country')}}</div>
              <dict-select v-model="listQuery.country" code="country" clearable></dict-select>
            </div>
          </el-col>
          <el-col :span="4">
            <div class="w20">
              <div class="labelName">Account</div>
              <el-input @keyup.enter.native="handleFilter" class="filter-item" v-model="listQuery.bu" clearable @blur="changeBu" :placeholder="$t('placeholder.content')"></el-input>
            </div>
          </el-col>
          <el-col :span="4">
            <div class="w20">
              <div class="labelName">Catergory</div>
              <el-select clearable v-model="listQuery.bg" :placeholder="$t('placeholder.choose')">
                <el-option v-for="item in bgList" :key="item.value" :label="item.label" :value="item.value" ></el-option>
              </el-select>
            </div>
          </el-col>
          <el-col :span="4">
            <div class="w20">
              <div class="labelName">{{$t('bu.name')}}</div>
              <el-input @keyup.enter.native="handleFilter" class="filter-item" v-model="listQuery.name" clearable :placeholder="$t('placeholder.content')"></el-input>
            </div>
          </el-col>
          <el-col :span="4" style="margin-top: 33px">
            <el-button class="yt-btn-ys" type="primary" icon="search" @click="handleFilter">{{ $t("button.search") }}</el-button>
            <el-button class="yt-btn" type="primary" @click="reset">{{ $t("button.reset") }}</el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="data-list">
      <div class="list-content">
        <span> {{ $t("bu.buList") }}</span>
      </div>
      <div class="list-operation">
        <!--新增-->
        <el-button type="primary" class="yt-btn-ys" @click="dictDialogVisible = true">{{ $t("button.new") }}</el-button>
        <!--保存-->
        <el-button type="primary" class="yt-btn" @click="handlePreserve">{{$t("button.preserve") }}</el-button>
        <!--删除-->
        <el-button type="primary" class="yt-btn" @click="handleDelete">{{$t("button.delete") }}</el-button>
      </div>

      <el-table :key="tableKey" border class="yt-table yt-temporary" :data="list" :empty-text="$t('placeholder.emptyText')" v-loading.body="listLoading" fit highlight-current-row @selection-change="handleSelectionChange" @sort-change="sortDate" max-height="600">
        <el-table-column align="center" type="selection" width="60" prop="id" />
        <el-table-column align="center" type="index" :label="$t('bu.serialNumber')" width="60"/>
        <el-table-column align="center" label="Account" sortable="custom" prop="bu" min-width="120px">
          <template slot-scope="scope">
            <el-input size="small" v-model="scope.row.bu"></el-input>
          </template>
        </el-table-column>
        <el-table-column align="center" label="Dept Type" sortable="custom" prop="buType" min-width="120px">
          <template slot-scope="scope">
            <dict-select v-model="scope.row.buType" code="BUType" :clearable="true"></dict-select>
          </template>
        </el-table-column>
        <el-table-column align="center" label="Catergory" sortable="custom" prop="bg" min-width="120px">
          <template slot-scope="scope">
            <dict-select v-model="scope.row.bg" code="BG" :clearable="true"></dict-select>
          </template>
        </el-table-column>
        <el-table-column align="center" :label="$t('bu.country')" sortable="custom" prop="country" min-width="120px">
          <template slot-scope="scope">
            <dict-select v-model="scope.row.country" code="country" :clearable="true"></dict-select>
          </template>
        </el-table-column>
        <el-table-column align="center" :label="$t('project.company')" class-name="pd" sortable="custom" prop="company" min-width="120px">
          <template slot-scope="scope">
            <dict-select v-model="scope.row.company" code="company" clearable></dict-select>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="source" align="center":label="$t('bu.source')"width="130" /> -->
        <el-table-column align="center" :label="$t('bu.operatingCostsNo')" sortable="custom" prop="operatingCostsNo" min-width="300px">
          <template slot-scope="scope">
            <el-input type="textarea" autosize size="small" v-model="scope.row.operatingCostsNo"></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="updateName" align="center" :label="$t('public.updateName')" sortable="custom" min-width="120px"/>
        <el-table-column prop="updateTime" align="center" :label="$t('public.updateTime')" sortable="custom" min-width="140px"/>
      </el-table>
      <div v-show="!listLoading" class="pagination-container">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" background :current-page.sync="listQuery.page" :page-sizes="[10, 20, 30, 50, 100, 200]" :page-size="listQuery.limit" layout="total, sizes, prev, pager, next, jumper" :total="total"></el-pagination>
      </div>
    </div>

    <el-dialog :title="$t('bu.newData')" :visible.sync="dictDialogVisible">
      <el-form ref="form" :model="addBu" label-width="100px">
        <el-form-item label="Catergory">
          <el-input v-model="addBu.bu"></el-input>
        </el-form-item>
        <el-form-item label="Dept Type">
          <template>
            <dict-select v-model="addBu.buType" code="BUType" :clearable="true"></dict-select>
          </template>
        </el-form-item>
        <el-form-item label="BU">
          <template>
            <dict-select v-model="addBu.bg" code="BG" :clearable="true"></dict-select>
          </template>
        </el-form-item>
        <el-form-item :label="$t('bu.country')">
          <template>
            <dict-select v-model="addBu.country" code="country" :clearable="true"></dict-select>
          </template>
        </el-form-item>
        <el-form-item :label="$t('bu.operatingCostsNo')">
          <el-input v-model="addBu.operatingCostsNo"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dictDialogVisible = false">{{
          $t("button.cancel")
        }}</el-button>
        <el-button type="primary" @click="editorDict">{{
          $t("button.determine")
        }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import { page, modify, delList, insertOne, listbgAndbu } from '@/api/bu/index';
  import formatter from '@/utils/formatter';
  import { mapGetters } from 'vuex';

  export default {
    name: 'buInfo',
    components: {
      'dict-select': () => import('@/components/Dict/dictValueSelect')
    },
    data() {
      return {
        config: Config.I18n,
        formatter,
        list: null, // 用于表格渲染数据
        total: null,
        tableListist: null, // 缓存原始数据
        listLoading: true,
        listQuery: {
          order: '', // 降序（desc）/升序（asc）
          orderBy: '', // 排序字段
          page: 1,
          limit: 10,
          country: '',
          bu: '',
          name: '',
          bg: ''
        },
        selectionList: [],
        tableKey: 0,
        dictDialogVisible: false,
        addBu: {
          bu: '',
          buType: '',
          bg: '',
          country: '',
          operatingCostsNo: ''
        },
        buList: [],
        bgList: []
      };
    },
    mounted() {
      this.getQuery();
      this.getList();
    },
    computed: {
      ...mapGetters(['elements'])
    },
    methods: {
      getQuery() {
        const searchBu = window.sessionStorage.getItem('searchBu');
        if (searchBu) {
          this.listQuery = JSON.parse(searchBu);
        }
        this.bgList = this.$store.getters.allDic.BG;
      },
      getList() {
        this.listLoading = true;
        page(this.listQuery).then(response => {
          response.data.rows.forEach(key => {
            if (key.departmentNo === '') {
              key.show = true
            } else {
              key.show = false
            }
          })
          this.list = response.data.rows;
          this.tableListist = JSON.parse(JSON.stringify(this.list));
          this.total = response.data.total;
          this.listLoading = false;
        });
      },
      handleFilter() {
        this.getList();
      },
      reset() {
        this.listQuery = {
          page: 1,
          limit: 10
        };
        this.getList();
        this.bgList = this.$store.getters.allDic.BG;
      },
      handleSizeChange(val) {
        this.listQuery.limit = val;
        window.sessionStorage.setItem('searchBu', JSON.stringify(this.listQuery));
        this.getList();
      },
      handleCurrentChange(val) {
        this.listQuery.page = val;
        this.getList();
      },
      handleSelectionChange(val) {
        //  表格序号选中函数
        this.selectionList = val;
      },
      // 删除
      handleDelete() {
        if (this.selectionList.length <= 0) {
          this.$notify({
            title: this.$t('bu.tips.fail'),
            message: this.$t('bu.tips.noChoice'),
            type: 'warning'
          });
          return;
        }
        const list = [];
        let show = true;
        for (let i = 0, flag = true, len = this.selectionList.length; i < len; flag ? i++ : i) {
          if (this.selectionList[i] && this.selectionList[i].departmentNo) {
            show = false;
            this.$alert(this.$t('bu.tips.filterTips'), this.$t('bu.tips.tips'), {
              confirmButtonText: this.$t('bu.tips.determine'),
              callback: () => {
                if (this.selectionList.length > 0) {
                  delList(list).then(res => {
                    this.$notify({
                      title:
                        res.status === 200
                          ? this.$t('bu.tips.success')
                          : this.$t('bu.tips.fail'),
                      message: res.data,
                      type: res.status === 200 ? 'success' : 'warning'
                    });
                    this.getList();
                  });
                }
              }
            });
            this.selectionList.splice(i, 1);
            flag = false;
          } else {
            flag = true;
            if (this.selectionList[i]) {
              list.push(this.selectionList[i].id);
            }
          }
        }
        if (show) {
          delList(list).then(res => {
            this.$notify({
              title:
                res.status === 200
                  ? this.$t('bu.tips.success')
                  : this.$t('bu.tips.fail'),
              message: res.data,
              type: res.status === 200 ? 'success' : 'warning'
            });
            this.getList();
          });
        }
      },
      // 新增数据
      editorDict() {
        this.addBu.departmentNo = ''
        this.addBu.departmentName = ''
        insertOne(this.addBu).then(res => {
          this.$notify({
            title:
              res.status === 200
                ? this.$t('bu.tips.success')
                : this.$t('bu.tips.fail'),
            message: res.status === 200 ? res.data : res.message,
            type: res.status === 200 ? 'success' : 'warning'
          });
          this.getList();
          this.dictDialogVisible = false;
        });
      },
      handlePreserve() {
        // 修改保存函数
        if (this.selectionList.length <= 0) {
          this.$notify({
            title: this.$t('bu.tips.fail'),
            message: this.$t('bu.tips.noChoice'),
            type: 'warning'
          });
          return;
        }
        const arr = []; // 存放已修改的
        this.selectionList.forEach(item => {
          if (
            JSON.stringify(this.tableListist).indexOf(JSON.stringify(item)) < 0
          ) {
            arr.push(item);
          }
        });
        modify(arr).then(res => {
          this.listLoading = false;
          this.$notify({
            title:
              res.status === 200
                ? this.$t('bu.tips.success')
                : this.$t('bu.tips.fail'),
            message: res.status === 200 ? res.data : res.message,
            type: res.status === 200 ? 'success' : 'warning'
          });
          this.getList();
        });
      },
      changeBu(val) {
        this.bgList = [];
        if (val.target.value === '') {
          return;
        }
        // 联动bg
        listbgAndbu({ bu: val.target.value, bg: '' }).then(res => {
          const list = this.$store.getters.allDic.BG;
          const data = res.data;
          list.forEach(item => {
            data.forEach(doc => {
              if (doc === item.value) {
                this.bgList.push(item);
              }
            });
          });
        });
      },
      // 排序
      sortDate(column) {
        console.log('column', column);
        // this.formatter.sortByKey(this.list, column.prop, column.order)
        if (column.order === 'ascending') {
          this.listQuery.order = 'asc';
        } else if (column.order === 'descending') {
          this.listQuery.order = 'desc';
        }
        this.listQuery.orderBy = column.prop;
        this.getList()
      }
      // changeBg(val) {
      //   // 联动bu
      //   listbgAndbu({ bu: '', bg: val }).then(res => {
      //     this.buList = res.data;
      //   });
      // }
    }
  };
</script>
